<template>
  <div class="pagination">
    <button @click="$emit('changePageNo',currentPageNo-1)">上一页</button>
    <button v-if="startEnd.start>1" @click="$emit('changePageNo',1)">1</button>
    <button v-if="startEnd.start>2">···</button>

    <button
        :class="{active:currentPageNo===page}"
        @click="$emit('changePageNo',page)" v-for="page in startEnd.end" :key="page" v-if="page>=startEnd.start">{{
        page
      }}
    </button>

    <!--    <button>3</button>-->
    <!--    <button>4</button>-->
    <!--    <button>5</button>-->
    <!--    <button>6</button>-->
    <!--    <button>7</button>-->

    <button v-if="startEnd.end<totalPage-1">···</button>
    <button v-if="startEnd.end<totalPage" @click="$emit('changePageNo',totalPage)">{{ totalPage }}</button>
    <button @click="$emit('changePageNo',currentPageNo+1)">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>

export default {
  name: "Pagination",
  props: {
    total: {//总商品数量
      type: Number,
      default: 0
    },
    currentPageNo: {//当前在第几页
      type: Number,
      default: 1
    },
    pageSize: Number,//每一页显示数量
    contineNum: Number,//中继页数量
  },
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    startEnd() {
      //计算中继页其实和结束应该如何分布
      const {totalPage, contineNum, currentPageNo} = this;
      let start, end;
      if (totalPage <= contineNum) {
        //如果总的页数比中继页数还少，则直接用中继页
        start = 1;
        end = contineNum;
      } else {
        //如果总的页数比中继页数多，则分情况考虑
        //中继页刚好在1-总页数中间，且没牵扯到1和总页数
        start = currentPageNo - Math.floor(contineNum / 2)
        end = currentPageNo + Math.floor(contineNum / 2)
        //假设中继页数为5 总页数为10
        //1 2 3 4 5 6 7 8 9 10
        if (currentPageNo < Math.ceil(contineNum / 2)) {
          //如果当前页小于3的话，则说明开开始页必须是1
          start = 1;
          end = contineNum;
        }
        if (currentPageNo >= totalPage - Math.ceil(contineNum / 2)) {
          //如果当前页小于8的话，则说结束页必须是最后一页
          start = totalPage - contineNum + 1;
          end = totalPage;
        }

      }


      return {start, end}
    },
  },

}
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
